<template>
  <div class="external-harvest-module">
    <el-tree
      v-loading="loading"
      :data="treeList"
      :props="defaultProps"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-on-click-node="true"
      node-key="id">
      <div slot-scope="{ node, data }" class="custom-tree-node">
        <div class="expend-btn">
          <img :src="getImg(node)" class="expend-icon" alt="">
        </div>
        <div v-if="data.isRoot" class="flex-one">
          {{ node.label }}
        </div>
        <div v-else :class="{'is-mobile': showMobilePage}" class="external-harvest-list">
          <div v-for="item in configList" :key="item.id" class="external-harvest-item">
            <div class="label">{{ item.label }}</div>
            <div v-if="!data._isEdit && !data._isAdd" class="val">
              <ToolTip v-if="item.id === 'postList'" :content="data.postList | arrJoin" />
              <ToolTip v-else :tool-tip="data[item.id] | moneyFilter" :content="data[item.id] | bigDataFilter(true, '',false,2)" />
            </div>
            <template v-else>
              <el-select
                v-if="item.id === 'postList'"
                v-model="data._EditPostList"
                :remote-method="getPostList"
                class="external-select"
                clearable
                multiple
                filterable
                remote
                collapse-tags
                size="small"
                placeholder="请选择">
                <el-option
                  v-for="item in postList"
                  :key="item"
                  :disabled="allUsePost.includes(item) && !data.postList.includes(item)"
                  :label="item"
                  :value="item"/>
              </el-select>
              <el-input
                v-else
                v-model="data[item.editKey]"
                class="external-input"
                type="number"
                oninput="if(value>1000000000)value=1000000000;"
                size="small"
                placeholder="请输入"
                @mousewheel.native.prevent>
                <!-- onchange="if(value<0)value=0" -->
                <!-- <span slot="suffix" class="input-unit">万</span> -->
              </el-input>
            </template>
          </div>
        </div>
        <div
          class="opeator">
          <div v-if="data.isRoot" class="button-text" @click.stop="addItem(node)">添加</div>
          <template v-else>
            <div v-if="!data._isEdit && !data._isAdd" class="button-text" @click.stop="toEdit(node, data)">编辑</div>
            <div v-if="!data._isEdit && !data._isAdd" class="button-text" @click.stop="deleteItem(data)">删除</div>
            <div v-if="data._isEdit || data._isAdd" class="button-text" @click.stop="submit(node, data)">保存</div>
            <div v-if="data._isEdit || data._isAdd" class="button-text" @click.stop="cancelItem(node, data)">取消</div>
          </template>
        </div>
      </div>
    </el-tree>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import { getAllPost } from '@/api/user';
import expend from '@/assets/setting/expend.png';
import expend_active from '@/assets/setting/expend-active.png';
import expend_active_no from '@/assets/setting/expend-active_no.png';
import ElMessage from '@/utils/message';
import { showModal } from '@/utils/message';
import { bigDataFilter, moneyFilter } from '@/filters/number';
import { getExternalHarvestList, editExternalHarvest, createExternalHarvest, deleteExternalHarvest } from '@/api/setting';

export default {
  name: 'ExternalHarvestModule',
  filters: { bigDataFilter, moneyFilter,
    arrJoin(arr) {
      if (!arr || arr.length === 0) return '';
      return arr.join(',');
    }
  },
  data() {
    return {
      loading: false,
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      treeList: [{
        id: 'ExternalHarvestId',
        label: '外采额度配置',
        isRoot: true,
        children: []
      }],
      postList: [],
      configList: [
        { label: '职位', id: 'postList', editKey: '_EditPostList' },
        { label: '外采额度', id: 'externalHarvestAmount', editKey: '_EditExternalHarvestAmount' },
        { label: '可授权外采额度', id: 'authAmount', editKey: '_EditAuthAmount' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    allUsePost() {
      let arr = [];
      this.treeList[0].children.forEach(i => {
        arr = arr.concat(i.postList);
      });
      return arr;
    }
  },
  created() {
    this.getList();
    this.getPostList();
  },
  methods: {
    getList() {
      getExternalHarvestList().then(res => {
        if (res.code === 200) {
          this.treeList[0].children = res.data;
        }
      });
    },
    submit(node, data) {
      if (!data._EditPostList || data._EditPostList.length === 0) {
        ElMessage.error('请选择职位');
        return;
      }
      if (!data._EditExternalHarvestAmount && data._EditExternalHarvestAmount !== 0) {
        ElMessage.error('请输入外采额度');
        return;
      }
      if (!data._EditAuthAmount && data._EditAuthAmount !== 0) {
        ElMessage.error('请输入可授权外采额度');
        return;
      }
      this.$set(data, 'postList', data._EditPostList);
      this.$set(data, 'externalHarvestAmount', data._EditExternalHarvestAmount);
      this.$set(data, 'authAmount', data._EditAuthAmount);
      delete data._EditPostList;
      delete data._EditExternalHarvestAmount;
      delete data._EditAuthAmount;
      const params = {
        postList: data.postList,
        externalHarvestAmount: data.externalHarvestAmount,
        authAmount: data.authAmount
      };
      this.loading = true;
      if (data._isEdit) {
        data._isEdit = false;
        params.id = data.id;
        this.edit(params);
      } else {
        data._isAdd = false;
        this.add(params);
      }
    },
    edit(params) {
      editExternalHarvest(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('编辑成功');
        } else {
          ElMessage.error(res.message);
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    add(params) {
      createExternalHarvest(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('新增成功');
          this.getList();
        } else {
          ElMessage.error(res.message);
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    toEdit(node, data) {
      this.$set(data, '_isEdit', true);
      this.$set(data, '_EditPostList', data.postList);
      this.$set(data, '_EditExternalHarvestAmount', data.externalHarvestAmount);
      this.$set(data, '_EditAuthAmount', data.authAmount);
    },
    addItem(node) {
      if (!node.expanded) this.$set(node, 'expanded', true);
      const isAdd = this.treeList[0].children.some(i => !!i._isAdd);
      if (isAdd) return;
      this.treeList[0].children.unshift({
        _isAdd: true,
        postList: [],
        authAmount: '',
        externalHarvestAmount: '',
        // 编辑状态下使用
        _EditPostList: [],
        _EditExternalHarvestAmount: '',
        _EditAuthAmount: ''
      });
    },
    cancelItem(node, data) {
      if (data._isAdd) {
        const index = this.treeList[0].children.findIndex(i => i._isAdd);
        this.treeList[0].children.splice(index, 1);
      } else {
        this.$set(data, '_isEdit', false);
        delete data._EditPostList;
        delete data._EditExternalHarvestAmount;
        delete data._EditAuthAmount;
      }
    },
    getImg(node) {
      if (!node.isLeaf && !node.expanded) return expend;
      else if (!node.isLeaf && node.expanded) return expend_active;
      else return expend_active_no;
    },
    // getData
    getPostList(name) {
      if (name) name = name.trim();
      const params = {
        page: 1,
        perPage: 20,
        name: name || ''
      };
      getAllPost(params).then(res => {
        if (res.data) {
          this.postList = res.data.items;
        }
      });
    },
    deleteItem(data) {
      showModal('请确认是否删除').then(_ => {
        const params = {
          id: data.id
        };
        deleteExternalHarvest(params).then(_ => {
          ElMessage.success('删除成功');
          this.getList();
        });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.external-harvest-module {
  &::v-deep {
    .el-tree {
      .el-tree-node {
        position: relative;
      }
      & > .el-tree-node {
        padding: 15px 1px;
        border-top: 1px solid #EBEEFD;
        position: relative;
        & > .el-tree-node__content {
          margin: 0;
        }
        &:nth-last-child(2) {
          border-bottom: none;
        }
      }
    }
    .el-tree-node__expand-icon {
      display: none;
    }
    .el-tree-node__content {
      background-color: #fff;
      height: auto;
      min-height: 32px;
      &:hover {
        background-color: #fff;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
}
.custom-tree-node {
  @include flexStyle($align:center, $flexOne: 1);
  width: 100%;
  font-size: 14px;
  .expend-icon {
    @include flexStyle($align:center, $justify:center);
    width: 16px;
    height: 16px;
  }
  .expend-btn {
    @extend .expend-icon;
    margin-right: 20px;
  }
}
.external-harvest-list {
  @include flexStyle($align:center);
  width: calc(100% - 36px - 134px);
  &.is-mobile {
    width: auto;
  }
  .external-harvest-item {
    @include flexStyle($align:center);
    width: 33.2%;
    padding-right: 10px;
    .label {
      font-size: 14px;
      color: #999;
      overflow: hidden;
      flex-shrink: 0;
    }
    .val {
      font-size: 14px;
      color: #333;
      margin-left: 10px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}
.opeator {
  width: 114px;
  margin-left: 20px;
  @include flexStyle($align:center);
  .button-text {
    margin-left: 10px;
  }
}
.external-select {
  margin-left: 10px;
  width: 100%;
  max-width: 200px;
  min-width: 100px;
  &::v-deep {
    .el-tag.el-tag--info {
      color: #406EFF !important;
      background-color: #EFF3FB !important;
    }
  }
}
.external-input {
  width: 100%;
  max-width: 200px;
  min-width: 100px;
  margin-left: 10px;
}
.input-unit {
  line-height: 32px;
}
</style>
